import {
  getSmsTemplateTable,
  editSmsTemplateRecord,
  deleteSmsTemplateRecord
} from '../../api/sms'
import {
  TEMPLATE_LIST,
  TEMPLATE_CURRENT_ROW,
  TEMPLATE_DATA_COUNT,
  TEMPLATE_HISTORY_DATA,
  TEMPLATE_PAGE_SIZE
} from '../motations-type'

export default {
  state: {
    templateList: [],
    templateDataCount: null,
    templatePageSize: 20,
    templateHistoryData: [],
    row: {
      ctime: '',
      content: '',
      smscontent: '',
      suffix: '',
      state: '',
      openstate: false,
      des: ''
    }
  },
  getters: {
    templateList: state => state.templateList
  },
  mutations: {
    [TEMPLATE_LIST] (state, data) {
      state.templateList = data
    },
    [TEMPLATE_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [TEMPLATE_DATA_COUNT] (state, data) {
      state.templateDataCount = data
    },
    [TEMPLATE_HISTORY_DATA] (state, data) {
      state.templateHistoryData = data
    },
    [TEMPLATE_PAGE_SIZE] (state, data) {
      state.templatePageSize = data
    }
  },
  actions: {
    async getSmsTemplateList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getSmsTemplateTable(data)
      // console.log(resp)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          id: item.id,
          ctime: item.ctime,
          content: item.content,
          // smscontent: item.smscontent,
          // suffix: item.suffix,
          state: item.state,
          tag: item.tag,
          des: item.des
        }]
      })
      commit(TEMPLATE_LIST, newData)
      commit(TEMPLATE_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.smsTemplate.templatePageSize) {
        commit(TEMPLATE_HISTORY_DATA, newData)
      } else {
        commit(TEMPLATE_HISTORY_DATA, newData.slice(0, rootState.smsTemplate.templatePageSize))
      }
      return resp
    },
    async editSmsTemplateData ({ commit, rootState }, playload) {
      let data = {}
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await editSmsTemplateRecord(data)
      return resp
    },
    async deleteSmsTemplateData ({ commit, rootState }, playload) {
      const resp = await deleteSmsTemplateRecord(playload)
      return resp
    },
    async getSmsTemplateCurrentRow ({ commit, rootState }, row) {
      commit(TEMPLATE_CURRENT_ROW, row)
    },
    async changeSmsTemplatePage ({ commit, rootState }, index) {
      let data = rootState.smsTemplate.templateList
      let _start = (index - 1) * rootState.smsTemplate.templatePageSize
      let _end = index * rootState.smsTemplate.templatePageSize
      commit(TEMPLATE_HISTORY_DATA, data.slice(_start, _end))
    },
    async changeSmsTemplatePageSize ({ commit, rootState }, value) {
      commit(TEMPLATE_PAGE_SIZE, value)
    }
  }
}
